package com.example.pclimb.ui.auth;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityChangePasswordBinding;
import com.example.pclimb.model.User;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.UserViewModel;

/**
 * 修改密码页面
 */
public class ChangePasswordActivity extends AppCompatActivity {

    private ActivityChangePasswordBinding binding;
    private UserViewModel userViewModel;
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityChangePasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置工具栏
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 初始化ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 获取当前用户信息
        int userId = SharedPreferencesUtil.getUserId(this);
        userViewModel.getUserById(userId).observe(this, user -> {
            if (user != null) {
                currentUser = user;
            } else {
                Toast.makeText(this, R.string.error_loading_user, Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        // 设置保存按钮点击事件
        binding.btnSave.setOnClickListener(v -> savePassword());
    }

    /**
     * 保存新密码
     */
    private void savePassword() {
        // 重置错误提示
        binding.tilCurrentPassword.setError(null);
        binding.tilNewPassword.setError(null);
        binding.tilConfirmPassword.setError(null);

        // 获取输入值
        String currentPassword = binding.etCurrentPassword.getText().toString().trim();
        String newPassword = binding.etNewPassword.getText().toString().trim();
        String confirmPassword = binding.etConfirmPassword.getText().toString().trim();

        // 验证输入
        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(confirmPassword)) {
            binding.tilConfirmPassword.setError(getString(R.string.error_field_required));
            focusView = binding.etConfirmPassword;
            cancel = true;
        } else if (!newPassword.equals(confirmPassword)) {
            binding.tilConfirmPassword.setError(getString(R.string.error_passwords_not_match));
            focusView = binding.etConfirmPassword;
            cancel = true;
        }

        if (TextUtils.isEmpty(newPassword)) {
            binding.tilNewPassword.setError(getString(R.string.error_field_required));
            focusView = binding.etNewPassword;
            cancel = true;
        } else if (newPassword.length() < 6) {
            binding.tilNewPassword.setError(getString(R.string.error_password_too_short));
            focusView = binding.etNewPassword;
            cancel = true;
        }

        if (TextUtils.isEmpty(currentPassword)) {
            binding.tilCurrentPassword.setError(getString(R.string.error_field_required));
            focusView = binding.etCurrentPassword;
            cancel = true;
        } else if (currentUser != null && !currentUser.getPassword().equals(currentPassword)) {
            binding.tilCurrentPassword.setError(getString(R.string.error_incorrect_password));
            focusView = binding.etCurrentPassword;
            cancel = true;
        }

        if (cancel) {
            // 输入有误，聚焦到错误输入框
            focusView.requestFocus();
        } else if (currentUser != null) {
            // 显示进度条
            showProgress(true);

            // 更新密码
            currentUser.setPassword(newPassword);

            // 保存用户信息
            userViewModel.update(currentUser);
            
            // 显示成功提示，并返回
            showProgress(false);
            Toast.makeText(this, R.string.password_updated, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * 显示或隐藏进度条
     */
    private void showProgress(boolean show) {
        binding.progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.btnSave.setEnabled(!show);
        binding.etCurrentPassword.setEnabled(!show);
        binding.etNewPassword.setEnabled(!show);
        binding.etConfirmPassword.setEnabled(!show);
    }
} 